﻿using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Data.SqlClient;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace WMSJWT.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        //认证中心
        [HttpGet]
        public JsonResult Login(string account, string pwd)
        {
            using (SqlConnection sqlConnection = new SqlConnection("Data Source=121.37.93.71;Initial Catalog=CSSL_ZCTWMS;User ID=sa;Password=geili@2025;Encrypt=False"))
            {
                string sql = $"select count(*) from [dbo].[zct_user] where user_account='{account}' and user_password='{pwd}'";
                int count = sqlConnection.QueryFirstOrDefault<int>(sql);
                //判断
                if (count > 0)
                {
                    //准备有效数据
                    var claims = new Claim[]
                    {
                     new Claim("account",account),
                     new Claim("pwd",pwd)
                    };

                    //读取加密key-32个字符
                    SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VFSS"));
                    //指定加密算法
                    SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    //创建jwt
                    JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                         issuer: "http://localhost:5178",//颁发Token的web应用程序地址(当前程序)
                         audience: "http://localhost:5194",//token接收程序的地址(WebApi)
                         claims: claims,
                         expires: DateTime.Now.AddMinutes(60),//60分钟有效
                         signingCredentials: signingCredentials
                        );
                    //生成jwt字符串
                    var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                    return new JsonResult(token);
                }
                else
                {
                    return new JsonResult("");
                }
            }
        }
    }
}
